<template>
	<div>
		<el-row type="flex" justify="space-around">
			<el-col :span="4" class="leftInfo">
				<!-- 树形 -->
				<div class="leftTop">
					<span>部门名称</span>
				</div>
				<el-tree accordion ref="treeinfo" class="treeInfo" check-on-click-node :data="treeInfo" :props="defaultProps"
				 @node-click="treeNodeClick" highlight-current node-key="id" :default-expanded-keys="expandedKeys"></el-tree>
			</el-col>
			<el-col :span="19" class="rightInfo">
				<!-- 搜索框 -->
				<el-form :inline="true" ref="searchForm" class="search" :model="searchForm" v-if="checkPermission(['sys:dept:search'])">
					<el-form-item label="部门名称:">
						<el-input size="mini" v-model="searchForm.name" clearable></el-input>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" icon="el-icon-search" size="small" @click="searchFormClick()">搜索</el-button>
						<el-button type="primary" size="small" @click="searchFormReset()">重置</el-button>
					</el-form-item>
				</el-form>
				<!-- 表格展示 -->
				<div class="tableInfo">
					<div class="leftButton">
						<el-button v-permission="['sys:dept:add']" type="primary" size="small" @click="AddClick()" :disabled="addButtonState">新增</el-button>
					</div>
					<el-table :data="tableData" style="width: 95%" highlight-current-row border :header-cell-style="{'text-align':'center'}"
					 :cell-style="{'text-align':'center'}">
						<el-table-column prop="departmentId" label="id"></el-table-column>
						<el-table-column prop="departmentName" label="部门名称"></el-table-column>
						<el-table-column prop="introduction" label="部门描述"></el-table-column>
						<el-table-column prop="creatTime" label="创建时间"></el-table-column>
						<el-table-column prop="updateTime" label="更新时间"></el-table-column>
						<el-table-column fixed="right" label="操作" v-if="checkPermission(['sys:dept:update','sys:dept:del'])">
							<template slot-scope="scope">
								<el-button v-permission="['sys:dept:update']" @click="EditClick(scope.row)" type="text" size="small">编辑</el-button>
								<el-button v-permission="['sys:dept:del']" @click="DeleteClick(scope.row)" type="text" size="small">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
					<el-pagination v-if="paginationState" @size-change="paginationSizeChange" @current-change="paginationCurrentChange"
					 :current-page="pageInfo.currentPage" :page-sizes="[10, 20, 30, 50]" :page-size="pageInfo.currentSize" layout="total, sizes, prev, pager, next, jumper"
					 :total="pageInfo.total">
					</el-pagination>
				</div>
			</el-col>
		</el-row>
		<!-- 用户新增的修改的弹窗 -->
		<div>
			<el-dialog :title="dialogName[dialogType]" width="25%" :visible.sync="addDialogShow" class="addUserInfo">
				<el-form :rules="rules" ref="ruleForm" :model="addInfoForm">
					<el-form-item label="部门名称" label-width="100px" prop="departmentName">
						<el-input clearable v-model="addInfoForm.departmentName" size="medium"></el-input>
					</el-form-item>
					<el-form-item label="部门描述" label-width="100px" prop="introduction">
						<el-input clearable v-model="addInfoForm.introduction" size="medium"></el-input>
					</el-form-item>
				</el-form>
				<div slot="footer" class="dialog-footer">
					<el-button @click="cancelForm()">取 消</el-button>
					<el-button v-if="resetButtonState" @click="resetForm()">重置</el-button>
					<el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
				</div>
			</el-dialog>
		</div>
	</div>
</template>

<script>
	//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
	//例如：import 《组件名称》 from '《组件路径》';
	import {
		getDepartmentTreeInfo,
		getDepartmentInfoByParentsId,
		deleteDepartmentInfo,
		modifyDepartmentInfo,
		addDepartmentInfo,
		searchDepartmentInfo
	} from '@/api/department.js'
	import Public from '@/views/mixin/PublicHandler.js'
	export default {
		mixins: [Public],
		data() {
			return {
				//搜索
				searchForm: {
					name: ''
				},
				//新增窗口状态显示
				addDialogShow: false,
				//当前树节点id
				currentTreeId: '',
				//添加信息
				addInfoForm: {
					departmentId: '',
					departmentName: '',
					introduction: '',
					parentId: ''
				},
				//表格信息
				tableData: [],
				//树信息
				treeInfo: [],
				//弹窗名字
				dialogName: ["新增部门", "修改部门"],
				//树默认选中节点
				expandedKeys: [],
				//弹出框类型 0 新增 1 修改
				dialogType: 0,
				//分页状态
				paginationState: true
			};
		},
		//监听属性 类似于data概念
		computed: {
			//新增按钮状态
			addButtonState() {
				if (!this.currentTreeId) {
					return true
				} else {
					return false
				}
			},
			//重置按钮状态
			resetButtonState() {
				if (this.dialogType === 1) {
					return false
				} else {
					return true
				}
			}
		},
		watch: {
			treeInfo() {
				this.paginationState = true
				if (!this.currentTreeId) {
					this.$nextTick(() => {
						this.$refs.treeinfo.setCurrentKey("1251544671117774848");
						this.currentTreeId = "1251544671117774848"
						this.getTableInfo()
						this.expandedKeys = ["1251544671117774848"]
					})
				} else {
					this.$nextTick(() => {
						this.$refs.treeinfo.setCurrentKey(this.currentTreeId);
						this.getTableInfo()
						this.expandedKeys = [this.currentTreeId]
					})
				}
			}
		},
		//方法集合
		methods: {
			searchFormReset() {
				this.searchForm = {}
				this.getLeftTreeInfo()
			},
			searchFormClick() {
				searchDepartmentInfo(this.searchForm).then(response => {
					const {
						data
					} = response
					this.tableData = data
				})
				this.currentTreeId = null
				this.expandedKeys = []
				this.$refs.treeinfo.setCurrentKey()
				this.paginationState = false
			},
			/**
			 * @param {Object} data
			 * 点击树的节点
			 */
			treeNodeClick(data) {
				this.currentTreeId = data.id
				this.getTableInfo()
			},
			/**
			 * @param {Object} data
			 * 页面条数更新
			 */
			paginationSizeChange(data) {
				this.pageInfo.currentSize = data
				this.getTableInfo()
			},
			/**
			 * @param {Object} data
			 * 页面数更新
			 */
			paginationCurrentChange(data) {
				this.pageInfo.currentPage = data
				this.getTableInfo()
			},
			/**
			 * 获取表数据
			 */
			getTableInfo() {
				const queryData = {
					departmentId: this.currentTreeId,
					page: this.pageInfo.currentPage,
					size: this.pageInfo.currentSize
				}
				getDepartmentInfoByParentsId(queryData).then(response => {
					const {
						data
					} = response
					this.tableData = data.records
					this.pageInfo.total = data.total
					this.pageInfo.currentPage = data.current
					this.pageInfo.currentSize = data.size
				}).catch(error => {
					console.log(error)
				})
			},
			/**
			 * 获取左侧树信息
			 */
			getLeftTreeInfo() {
				getDepartmentTreeInfo().then(response => {
					const {
						data
					} = response
					this.treeInfo = data
				}).catch(error => {
					console.log(error)
				})
			},
			/**
			 * @param {Object} formName 新增部门表单重置
			 */
			resetForm() {
				this.addInfoForm = {}
			},
			/**
			 * 
			 * @param {Object} formName
			 */
			cancelForm() {
				this.resetForm()
				this.addDialogShow = false
			},
			/**
			 * @param {Object} formName 新增部门表单提交
			 */
			submitForm(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						if (this.dialogType === 1) {
							this.addInfoForm.parentId = this.currentTreeId
							this.editDepartment()
						} else {
							this.addDepartment()
						}
						this.addDialogShow = false
						return true
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			addDepartment() {
				this.addInfoForm.parentId = this.currentTreeId
				addDepartmentInfo(this.addInfoForm).then(response => {
					this.$message({
						type: 'success',
						message: '部门添加成功'
					})
					this.getLeftTreeInfo()
				})
			},
			editDepartment() {
				this.$confirm("此操作将修改该记录, 是否继续", "提示", {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					modifyDepartmentInfo(this.addInfoForm).then(response => {
						this.$message({
							type: 'success',
							message: '修改成功!'
						});
						this.getLeftTreeInfo()
					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '修改已取消'
					})
				})
			},

			/**
			 * 编辑按钮
			 * @param {Object} row
			 */
			EditClick(row) {
				this.dialogType = 1
				this.addInfoForm = Object.assign({}, row)
				this.addDialogShow = true
			},
			/**
			 * 删除按钮
			 * @param {Object} row
			 */
			DeleteClick(row) {
				this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					deleteDepartmentInfo(row.departmentId).then(response => {
						this.$message({
							type: 'success',
							message: '删除成功!'
						});
						this.getLeftTreeInfo()
					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				})

			},
			AddClick() {
				this.dialogType = 0
				this.addInfoForm = {
					type: 0
				}
				this.addDialogShow = true
			}
		},
		//生命周期 - 创建完成（可以访问当前this实例）
		created() {
			this.getLeftTreeInfo()
			this.rules = {
				departmentName: [{
					required: true,
					message: '请输入部门名称',
					trigger: 'blur'
				}],
				introduction: [{
					required: true,
					message: '请输入部门描述',
					trigger: 'blur'
				}],
			}
		},
		//生命周期 - 挂载完成（可以访问DOM元素）
		mounted() {}
	};
</script>
<style scoped lang="scss">
	.leftInfo {
		border: #001528;
		background-color: #ffffff;
		margin-top: 0.625rem;
		border-radius: 14px;
		box-shadow: 10px 10px 5px rgba(100, 100, 100, .5);

		.leftTop {
			text-align: center;
			font-size: 23px;
			border-bottom-style: solid;
			border-width: 4px;
			border-color: #F3F3F4;
		}

		.treeInfo {
			margin: 20px 10px 20px 20px;
		}
	}

	.rightInfo {
		.tableInfo {
			background-color: #ffffff;
			margin-top: 0.625rem;
			min-height: 208px;
			border-radius: 10px;
			box-shadow: 10px 10px 5px rgba(100, 100, 100, .5);
			padding-bottom: 20px;

			.leftButton {
				padding-left: 1.9375rem !important;
				padding-top: 10px;
			}

			.el-table {
				margin-top: 0.625rem;
				margin-left: auto;
				margin-right: auto;
				margin-bottom: 20px;
				font-size: 15px;
			}

			.el-pagination {
				margin-left: 1.375rem;
				padding-top: 10px;
				padding-bottom: 20px;
			}
		}

		.search {
			margin-top: 0.625rem;
			border-radius: 5px;
			background-color: #FFFFFF;
			display: flex;
			flex-direction: row;
			justify-content: space-around;
			box-shadow: 10px 10px 5px rgba(100, 100, 100, .5);

			.el-form-item {
				margin-bottom: 0 !important;
				margin-left: 20px;
			}
		}
	}

	.addUserInfo {
		.el-input {
			width: 13.5rem;
		}

		.el-form-item {
			padding-left: 10px;
		}
	}
</style>
